<template>
  <div class="app-container">
    <div class="card-box">
      <el-button type="primary" @click="handleCreate">添加API Key</el-button>
    </div>
    <div class="card-box">
      <el-table v-loading="apiKeyStore.loading.list" :data="apiKeyStore.list" style="width: 100%">
        <el-table-column prop="key" label="API Key" />
        <el-table-column label="所属应用" prop="app.name" />
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="created_at" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-popconfirm title="确定删除?" placement="top" @confirm="handleDelete(row)">
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-model:page="listQuery.page"
        v-model:limit="listQuery.size"
        :total="apiKeyStore.totalCount"
        @pagination="apiKeyStore.fetchList(listQuery)"
      />
    </div>
    <Form v-model="visible" :type="formType" :form="currentRow" @confirm="handleConfirm" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useApiKeyStoreHook } from "@/store/modules/system/api-key";
import Form, { type FormType } from "./components/form.vue";
import Pagination from "@/components/Pagination/index.vue";
import { ApiKeyForm, ApiKeyType } from "@/api/system/api-key";

const apiKeyStore = useApiKeyStoreHook();

const listQuery = reactive({
  page: 1,
  size: 20,
});

const visible = ref(false);
const formType = ref<FormType>("add");

const currentRow = ref<ApiKeyForm>({
  app: "",
  is_active: true,
  key: "",
});

onMounted(async () => {
  await apiKeyStore.fetchList(listQuery);
});

function handleCreate() {
  formType.value = "add";
  currentRow.value = {
    app: "",
    is_active: true,
    key: "",
  };
  visible.value = true;
}

function handleEdit(row: ApiKeyType) {
  formType.value = "edit";
  currentRow.value = {
    id: row.id,
    app: row.app.id,
    is_active: row.is_active,
    key: row.key,
  };
  visible.value = true;
}

async function handleDelete(row: ApiKeyType) {
  await apiKeyStore.fetchDelete(row.id);
  apiKeyStore.fetchList(listQuery);
}

function handleConfirm() {
  apiKeyStore.fetchList(listQuery);
}
</script>
